package com.springmvc.handler;

import com.springmvc.RequestMappingInfo;
import com.springmvc.annotation.RequestMapping;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
public class AnnotationHandlerMapper implements HandlerMapping{

    static Map<String, RequestMappingInfo> map = new HashMap<>();

    @Override
    public Object getHandler(String url) {
        return map.get(url);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            // 如果当前方法上，存在RequestMapping注解
            if (method.isAnnotationPresent(RequestMapping.class)) {
                RequestMappingInfo mappingInfo = createMethodInfo(method);
                mappingInfo.setBean(bean);
                map.put(mappingInfo.getUrl(), mappingInfo);
            }
        }
        return true;
    }


    /** 创建请求方法信息 */
    private RequestMappingInfo createMethodInfo(Method method) {
        RequestMappingInfo info = new RequestMappingInfo();
        info.setMethod(method);
        // 获取方法上RequestMapping注解中的请求路径
        String url = method.getAnnotation(RequestMapping.class).value();
        info.setUrl(url);
        return info;
    }

}
